package com.xuecheng.system.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.config.MD5Util;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mapper.UserMapper;
import com.xuecheng.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private RedisTemplate redisTemplate;


    // 用户登录
    @Override
    public ResponseResult login(LoginDto dto) {
        // 1.非空判断
        String username = dto.getUsername();
        String password = dto.getPassword();
        String utype = dto.getUtype();
        // 有一个不合法，就返回自定义异常
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password) || StrUtil.isBlank(utype)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        // 2.根据username+utype查询数据库
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, username);
        qw.eq(User::getUtype, utype);
        User user = this.getOne(qw); // 调用本类的方法
        // 3.判断用户是否存在
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        // 4.判断密码是否正确
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5, user.getPassword())) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        // 5.登录成功，jwt制作token
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("companyId", user.getCompanyId());
        map.put("companyName", user.getCompanyName());
        String token = JwtUtils.createToken(map);
        // 6.user存入redis（敏感数据+有效期）
        redisTemplate.opsForValue().set(UserConstants.USER_ID + user.getId(), user, Duration.ofMinutes(180));
        // 7.返回结果
        LoginVo vo = new LoginVo();
        vo.setAccess_token(token);
        vo.setUsername(user.getPhone());
        return ResponseResult.okResult(vo);
    }

    //验证手机验证码
    @Override
    public ResponseResult verify(String phone, String code) {

        // 1.比较验证码是否正确
        // 1-1 取出redis
        String codeFromRedis = (String) redisTemplate.opsForValue().get("code:" + phone);
        // 1-2 比较
        if (!StrUtil.equals(code, codeFromRedis)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        return ResponseResult.okResult(true);
    }

    //修改密码
    @Override
    public ResponseResult changePwd(String password, String confirmPwd, String phone) {
        //判断参数
        if (!password.equals(confirmPwd) || StrUtil.isEmpty(password) || StrUtil.isEmpty(confirmPwd)) {
           throw  new BusinessException(ErrorCode.PARAMSERROR);
        }
        //将新密码加密
        //SecureUtil.md5()
        String md5 = MD5Util.md5(password);
        //根据手机号查询账户原始密码
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = this.getOne(wrapper);
        //判断新老密码是否一样,如果一样返回错误信息
        if (md5.equals(user.getPassword())) {
            throw new BusinessException(ErrorCode.MIMACHONGFU);
        }
        //新密码覆盖旧密码
        user.setPassword(md5);
        //修改
        this.updateById(user);
        //返回结果
        return ResponseResult.okResult(true);
    }


}
